import { BaseEntity } from './BaseEntity';

/**
 * 技能实体类
 */
export class Skill extends BaseEntity {
    /** 技能名称 */
    public name: string;
    
    /** 技能重命名（玩家自定义名称） */
    public customName?: string;
    
    /** 技能描述 */
    public description: string;
    
    /** 技能类型 */
    public type: SkillType;
    
    /** 技能图标 */
    public icon: string;
    
    /** 技能等级 */
    public level: number;
    
    /** 最大等级 */
    public maxLevel: number;
    
    /** 冷却时间（毫秒） */
    public cooldown: number;
    
    /** 消耗魔法值 */
    public mpCost: number;
    
    /** 技能伤害 */
    public damage: number;
    
    /** 技能范围 */
    public range: number;
    
    /** 技能效果 */
    public effects: SkillEffect[];
    
    /** 学习要求 */
    public requirements: SkillRequirements;
    
    /** 使用次数 */
    public useCount: number;
    
    /** 永久加成 */
    public permanentBoosts: Record<string, number>;
    
    /** 技能数据 */
    public data: SkillData;
    
    /** 是否为被动技能 */
    public isPassive: boolean;
    
    /** 是否为光环技能 */
    public isAura: boolean;
    
    /** 技能标签 */
    public tags: string[];

    constructor(id?: string) {
        super(id);
        
        this.name = '';
        this.description = '';
        this.type = SkillType.ACTIVE;
        this.icon = '';
        this.level = 1;
        this.maxLevel = 10;
        this.cooldown = 0;
        this.mpCost = 0;
        this.damage = 0;
        this.range = 1;
        this.effects = [];
        this.requirements = {
            level: 1,
            attributes: {},
            skills: []
        };
        this.useCount = 0;
        this.permanentBoosts = {};
        this.data = {};
        this.isPassive = false;
        this.isAura = false;
        this.tags = [];
    }

    /**
     * 创建技能
     */
    public static create(config: SkillCreateConfig): Skill {
        const skill = new Skill(config.id);
        
        skill.name = config.name;
        skill.customName = config.customName;
        skill.description = config.description || '';
        skill.type = config.type || SkillType.ACTIVE;
        skill.icon = config.icon || '';
        skill.level = config.level || 1;
        skill.maxLevel = config.maxLevel || 10;
        skill.cooldown = config.cooldown || 0;
        skill.mpCost = config.mpCost || 0;
        skill.damage = config.damage || 0;
        skill.range = config.range || 1;
        skill.effects = config.effects || [];
        skill.requirements = config.requirements || {
            level: 1,
            attributes: {},
            skills: []
        };
        skill.useCount = config.useCount || 0;
        skill.permanentBoosts = config.permanentBoosts || {};
        skill.data = config.data || {};
        skill.isPassive = config.isPassive || false;
        skill.isAura = config.isAura || false;
        skill.tags = config.tags || [];
        
        return skill;
    }

    /**
     * 升级技能
     */
    public levelUp(): LevelUpResult {
        if (this.level >= this.maxLevel) {
            return {
                success: false,
                message: '技能已达到最大等级',
                newLevel: this.level
            };
        }

        this.level += 1;
        
        // 技能升级时提升属性
        this.damage = Math.floor(this.damage * 1.1);
        this.mpCost = Math.floor(this.mpCost * 1.05);
        
        // 某些等级可能减少冷却时间
        if (this.level % 3 === 0) {
            this.cooldown = Math.max(0, this.cooldown - 100);
        }

        this.updateEntity();

        return {
            success: true,
            message: `技能 ${this.getDisplayName()} 升级到 ${this.level} 级`,
            newLevel: this.level
        };
    }

    /**
     * 获取显示名称
     */
    public getDisplayName(): string {
        return this.customName || this.name;
    }

    /**
     * 设置自定义名称
     */
    public setCustomName(name: string): void {
        this.customName = name.trim() || undefined;
        this.updateEntity();
    }

    /**
     * 使用技能
     */
    public use(): UseResult {
        if (this.isPassive) {
            return {
                success: false,
                message: '被动技能无法主动使用',
                effects: []
            };
        }

        this.useCount += 1;
        this.updateEntity();

        return {
            success: true,
            message: `使用技能：${this.getDisplayName()}`,
            effects: this.effects
        };
    }

    /**
     * 检查是否满足学习要求
     */
    public checkRequirements(playerLevel: number, playerAttributes: Record<string, number>, learnedSkills: string[]): RequirementCheckResult {
        const failedRequirements: string[] = [];

        // 检查等级要求
        if (playerLevel < this.requirements.level) {
            failedRequirements.push(`需要等级 ${this.requirements.level}`);
        }

        // 检查属性要求
        for (const [attr, required] of Object.entries(this.requirements.attributes)) {
            if ((playerAttributes[attr] || 0) < required) {
                failedRequirements.push(`需要 ${attr} ${required}`);
            }
        }

        // 检查前置技能要求
        for (const requiredSkill of this.requirements.skills) {
            if (!learnedSkills.includes(requiredSkill)) {
                failedRequirements.push(`需要学习技能：${requiredSkill}`);
            }
        }

        return {
            canLearn: failedRequirements.length === 0,
            failedRequirements
        };
    }

    /**
     * 获取技能伤害（考虑等级加成）
     */
    public getActualDamage(): number {
        const levelMultiplier = 1 + (this.level - 1) * 0.1;
        return Math.floor(this.damage * levelMultiplier);
    }

    /**
     * 获取实际冷却时间（考虑等级减免）
     */
    public getActualCooldown(): number {
        const levelReduction = Math.floor((this.level - 1) / 3) * 100;
        return Math.max(0, this.cooldown - levelReduction);
    }

    /**
     * 获取实际魔法消耗（考虑等级增加）
     */
    public getActualMpCost(): number {
        const levelMultiplier = 1 + (this.level - 1) * 0.05;
        return Math.floor(this.mpCost * levelMultiplier);
    }

    /**
     * 获取技能效率评分
     */
    public getEfficiencyScore(): number {
        if (this.mpCost === 0) return 100;
        return Math.round((this.getActualDamage() / this.getActualMpCost()) * 10);
    }

    /**
     * 验证技能数据
     */
    public validate(): any {
        const result = super.validate();

        if (!this.name || this.name.trim().length === 0) {
            result.errors.push({ field: 'name', message: '技能名称不能为空' });
        }

        if (this.level < 1 || this.level > this.maxLevel) {
            result.errors.push({ field: 'level', message: `技能等级必须在1-${this.maxLevel}之间` });
        }

        if (this.cooldown < 0) {
            result.errors.push({ field: 'cooldown', message: '冷却时间不能为负数' });
        }

        if (this.mpCost < 0) {
            result.errors.push({ field: 'mpCost', message: '魔法消耗不能为负数' });
        }

        if (this.damage < 0) {
            result.errors.push({ field: 'damage', message: '技能伤害不能为负数' });
        }

        result.isValid = result.errors.length === 0;
        return result;
    }
}

/**
 * 技能类型枚举
 */
export enum SkillType {
    ACTIVE = 'active',      // 主动技能
    PASSIVE = 'passive',    // 被动技能
    AURA = 'aura',         // 光环技能
    BUFF = 'buff',         // 增益技能
    DEBUFF = 'debuff',     // 减益技能
    HEAL = 'heal',         // 治疗技能
    DAMAGE = 'damage',     // 伤害技能
}

/**
 * 技能效果接口
 */
export interface SkillEffect {
    type: string;           // 效果类型
    value: number;          // 效果数值
    duration: number;       // 持续时间
    target: SkillTarget;    // 作用目标
    condition?: string;     // 触发条件
}

/**
 * 技能目标枚举
 */
export enum SkillTarget {
    SELF = 'self',          // 自己
    ENEMY = 'enemy',        // 敌人
    ALLY = 'ally',          // 队友
    ALL_ENEMIES = 'all_enemies',    // 所有敌人
    ALL_ALLIES = 'all_allies',      // 所有队友
    AREA = 'area',          // 区域
}

/**
 * 技能要求接口
 */
export interface SkillRequirements {
    level: number;                      // 等级要求
    attributes: Record<string, number>; // 属性要求
    skills: string[];                   // 前置技能要求
}

/**
 * 技能数据接口
 */
export interface SkillData {
    [key: string]: any;
}

/**
 * 技能创建配置接口
 */
export interface SkillCreateConfig {
    id?: string;
    name: string;
    customName?: string;
    description?: string;
    type?: SkillType;
    icon?: string;
    level?: number;
    maxLevel?: number;
    cooldown?: number;
    mpCost?: number;
    damage?: number;
    range?: number;
    effects?: SkillEffect[];
    requirements?: SkillRequirements;
    useCount?: number;
    permanentBoosts?: Record<string, number>;
    data?: SkillData;
    isPassive?: boolean;
    isAura?: boolean;
    tags?: string[];
}

/**
 * 升级结果接口
 */
export interface LevelUpResult {
    success: boolean;
    message: string;
    newLevel: number;
}

/**
 * 使用结果接口
 */
export interface UseResult {
    success: boolean;
    message: string;
    effects: SkillEffect[];
}

/**
 * 要求检查结果接口
 */
export interface RequirementCheckResult {
    canLearn: boolean;
    failedRequirements: string[];
}
